package com.huluobo.base.net

import com.blankj.utilcode.util.EncryptUtils
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject
import kotlin.math.abs

/**
 *  Created by LC on 2024/8/8.
 */
class SignInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val builder = request.newBuilder()

        val body = chain.request().body
        val buffer = Buffer()
        body?.writeTo(buffer)
        val bodyStr = buffer.toString()
        buffer.close()

        val jsonStr = bodyStr.substring(bodyStr.indexOf("{"), bodyStr.lastIndexOf("}") + 1)

        val sb = StringBuffer()
        val jsonObj = JSONObject(jsonStr)
        val keys = jsonObj.keys()
        while (keys.hasNext()) {
            val key = keys.next()
            val value = jsonObj.getString(key)
            sb.append(value)
        }
        sb.append("tamboo")
        val sign = EncryptUtils.encryptMD5ToString(sb.toString()).toLowerCase()
        jsonObj.put("sign", sign)
        val requestBody = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), jsonObj.toString())
        builder.post(requestBody)
        request = builder.build()
        return chain.proceed(request)

    }
}